<template>
	<view>
		<!-- 绘制canvas -->
		<canvas class="mycanvas" :style="'width:290px;height:600px'" canvas-id="mycanvas"></canvas>
		<block>
			<!-- 展示图片 -->
			<image class="imgs" :style="'width:290px;height:600px'" :src="imgUrl" mode=""></image>
		</block>
		<!-- #ifndef H5 -->
		<view class="saveImg" @tap="saveImg" style="background: #7A54D6">
			保存图片
		</view>
		<!-- #endif -->
		<!-- #ifdef H5 -->
		<p class="tips">长按图片进行保存</p>
		<!-- #endif -->
	</view>
</template>

<script>
	import uQRCode from './uqrcode.js'

	export default {
		mixins: [{
			methods: {
				setData: function(obj, callback) {
					let that = this;
					const handleData = (tepData, tepKey, afterKey) => {
						tepKey = tepKey.split('.');
						tepKey.forEach(item => {
							if (tepData[item] === null || tepData[item] === undefined) {
								let reg = /^[0-9]+$/;
								tepData[item] = reg.test(afterKey) ? [] : {};
								tepData = tepData[item];
							} else {
								tepData = tepData[item];
							}
						});
						return tepData;
					};
					const isFn = function(value) {
						return typeof value == 'function' || false;
					};
					Object.keys(obj).forEach(function(key) {
						let val = obj[key];
						key = key.replace(/\]/g, '').replace(/\[/g, '.');
						let front, after;
						let index_after = key.lastIndexOf('.');
						if (index_after != -1) {
							after = key.slice(index_after + 1);
							front = handleData(that, key.slice(0, index_after), after);
						} else {
							after = key;
							front = that;
						}
						if (front.$data && front.$data[after] === undefined) {
							Object.defineProperty(front, after, {
								get() {
									return front.$data[after];
								},
								set(newValue) {
									front.$data[after] = newValue;
									that.$forceUpdate();
								},
								enumerable: true,
								configurable: true
							});
							front[after] = val;
						} else {
							that.$set(front, after, val);
						}
					});
					isFn(callback) && this.$nextTick(callback);
				}
			}
		}],
		data() {
			return {
				windowWidth: '',
				windowHeight: '',
				colors: "#fa436a",
				ctx: '',
				imgUrl: '',
				isShow: false,

			};
		},


		props: {
			// 海报生成数据
			posterData: {
				type: Object
			}
		},
		created() {
			this.getSystem();

			this.setPoster();
		},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {},

		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {},
		methods: {
			getSystem() {
				let that = this;
				uni.getSystemInfo({
					success: function(res) {
						console.log(res);
						that.setData({
							windowHeight: res.windowHeight,
							windowWidth: res.windowWidth
						});
					}
				});
			},

			setPoster() {
				uni.showLoading({
					title: '海报生成中...'
				})
				let ctx = uni.createCanvasContext('mycanvas', this); // 绘制背景
				// ctx.fillStyle = "#FFFFFF"
				ctx.fillRect(0, 0, 290, 600)
				// 绘制商品图片
				let width = 290
				let height = 600
				ctx.drawImage(this.posterData.bgImage, 0, 0, width, height);
				ctx.save();
				// 绘制二维码
				this.setEwm(ctx);
			},

			setEwm(ctx) {
				console.log('生成二维码')
				let code_widht = 101; //二维码宽度
				let code_height = 101; //二维码高度
				// let x = (this.windowWidth - 160)/2
				let x = (290 - code_widht)/2
				let myThis = this;
				uQRCode.make({
					canvasId: 'mycanvas',
					componentInstance: this,
					text: this.posterData.url,
					size: 160,
					margin: 10,
					fileType: 'png',
					success: res => {
						console.log('生成二维码3')

						console.log('res = ' + res);

						ctx.drawImage(res, x, 285, code_widht, code_height);

						setTimeout(() => { //必须延时执行 不然h5不显示
							ctx.save();
							ctx.draw(false, () => {
								setTimeout(() => {
									uni.canvasToTempFilePath({
										canvasId: 'mycanvas',
										success: (res) => {
											console.log(res)
											this.imgUrl = res.tempFilePath
										}
									}, this)
								}, 300)
							})
							uni.hideLoading()
						}, 1000)

					},
					complete: () => {

					}
				})


			},
			saveImg() {
				//保存图片
				uni.showLoading({
					title: '保存中...'
				});
				let that = this;
				// #ifdef MP
				uni.getSetting({
					success(res) {
						uni.hideLoading();
						console.log(res)
						if (!res.authSetting['scope.writePhotosAlbum']) {
							wx.authorize({
								scope: 'scope.writePhotosAlbum',
								success: (res) => {
									console.log(res)
								}
							})
						} else {
							setTimeout(() => {
								uni.saveImageToPhotosAlbum({
									filePath: that.imgUrl,
									success(re) {
										uni.hideLoading();
										uni.showToast({
											title: '保存成功',
											icon: 'success'
										});
									},
									fail(err) {
										console.log(err);
										uni.showToast({
											title: '保存失败',
											icon: 'none'
										});
									}

								});
							}, 1000);
						}
					}

				});
				// #endif
				// #ifdef APP-PLUS
				setTimeout(() => {
					uni.saveImageToPhotosAlbum({
						filePath: that.imgUrl,
						success(re) {
							uni.hideLoading();
							uni.showToast({
								title: '保存成功',
								icon: 'success'
							});
						},
						fail(err) {
							console.log(err);
							uni.showToast({
								title: '保存失败',
								icon: 'none'
							});
						}

					});
				}, 1000);
				// #endif
			}
		}
	};
</script>
<style scoped>
	.mycanvas {
		margin: 0 auto;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.saveImg {
		width: 70%;
		height: 80upx;
		line-height: 80upx;
		text-align: center;
		border-radius: 40rpx;
		margin: 40upx auto 20upx;
		color: white;
	}

	.imgs {
		position: absolute;
		top: 0;
		left: 50%;
		border-radius: 20upx;
		transform: translateX(-50%);
		/* 遮挡二维码 */
		background-color: white;
		/* 置于上层 */
		z-index: 99;
	}

	.tips {
		text-align: center;
		color: #fff;
		font-size: 24upx;
		margin-top: 20upx;
	}
</style>
